package com.laicunba.ext.service.impl;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.ibatis.session.SqlSession;
import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import com.laicunba.ext.service.SlaveQueryService;
import com.laicunba.util.StringUtil;

@Service
public class SlaveQueryServiceImpl extends BaseService implements SlaveQueryService {
	@Autowired
	@Qualifier("SqlSessionTemplateSlave")
	protected SqlSessionTemplate session;

	@Override
	public List<Map<String, Object>> query(String sqlId, HashMap param) {
		return this.slaveGenericQueryDao.selectList(sqlId, param);
	}

	@Override
	public List<Map<String, Object>> executeSelect(String selectSql) {
		if (StringUtil.isEmpty(selectSql)) {
			return null;
		}

		if (!selectSql.split(" ")[0].equalsIgnoreCase("select")) {
			return null;
		}
		Connection conn = null;
		SqlSession sqlSession = null;
		try {
			sqlSession = session.getSqlSessionFactory().openSession();
			conn = sqlSession.getConnection();
			Statement stmt = conn.createStatement();
			ResultSet rs = stmt.executeQuery(selectSql);
			ResultSetMetaData rsmd = rs.getMetaData();

			List<Map<String, Object>> list = new ArrayList();
			while (rs.next()) {
				Map<String, Object> map = new HashMap();
				int columnCount = rsmd.getColumnCount();
				for (int i = 0; i < columnCount; i++) {
					String name = rsmd.getColumnName(i + 1);
					String value = rs.getString(i + 1);
					map.put(name, value == null ? "NULL" : value);
				}

				list.add(map);
			}
			return list;
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			sqlSession.close();

		}
		return null;

	}

}
